import time

def timestampToDailyMonthlyAnnuallyTimestamp(timestamp):
    '''輸入當前秒級時間戳，返回對應本日，本月，本年的秒級時間戳'''
    '''返回值為字典，包括daily,monthly,annually'''
    ts = time.localtime(timestamp)
    dailyTs = time.strptime('%d-%d-%d'%(ts.tm_year, ts.tm_mon, ts.tm_mday), '%Y-%m-%d')
    monthlyTs = time.strptime('%d-%d-1'%(ts.tm_year, ts.tm_mon), '%Y-%m-%d')
    annuallyTs = time.strptime('%d-1-1'%(ts.tm_year), '%Y-%m-%d')
    dailyTimestamp = time.mktime(dailyTs)
    monthlyTimestamp = time.mktime(monthlyTs)
    annuallyTimestamp = time.mktime(annuallyTs)
    return {\
        'daily':int(dailyTimestamp),\
        'monthly':int(monthlyTimestamp),\
        'annually':int(annuallyTimestamp)}

def timestampToString(timestamp):
    ts = time.localtime(timestamp)
    return time.strftime("%Y-%m-%d %H:%M", ts)

def timestampFromString(string):
    ts = time.strptime(string, "%Y-%m-%d %H:%M")
    return int(time.mktime(ts))

def cat1TypeStrToInt(cat1Str):
    if cat1Str == "Income":
        return 1
    if cat1Str == "Payment":
        return 2
    if cat1Str == "Transfer":
        return 3
    raise ValueError("cat1 string is not correct")

def cat1TypeIntToString(t):
    if type(t) != int:
        raise ValueError("type must be int type!")
    if t == 2 :
        return "Payment"
    elif t == 1 :
        return "Income"
    elif t == 3 :
        return "Transfer"
    else :
        raise ValueError("type value is not correct!")

def cutTimestampByDay(timestamp):
    ts = time.localtime(timestamp)
    ts = time.strptime('%d-%d-%d'%(ts.tm_year, ts.tm_mon, ts.tm_mday), '%Y-%m-%d')
    return int(time.mktime(ts))
    
def cutTimestampByMonth(timestamp):
    ts = time.localtime(timestamp)
    ts = time.strptime('%d-%d-1'%(ts.tm_year, ts.tm_mon), '%Y-%m-%d')
    return int(time.mktime(ts))

def cutTimestampByYear(timestamp):
    ts = time.localtime(timestamp)
    ts = time.strptime('%d-1-1'%(ts.tm_year), '%Y-%m-%d')
    return int(time.mktime(ts))

def fenToYuanStr(fen):
    '''把單位為（分）的整數轉換為單位為（元）的字符串'''
    isNegative = False
    if fen < 0:
        isNegative = True
        fen = 0 - fen
    yuan = fen // 100
    fen = fen % 100
    if fen == 0:
        retStr = str(yuan)
    else:
        retStr = str(yuan) + '.' + str(fen)
    if isNegative == True:
        retStr = '-' + retStr
    return retStr

def generateEmptyBudgetConfigFile(paymentCat1List, fileAbsoluteName):
    ''' 生成一個未填寫數據的預算配置文件
    paymentCat1List: 所有一級支出分類的類別，形如[(ID, NAME, SHOWABLE) ... ]
    fileAbsoluteName: 配置文件的絕對路徑（包含文件名）
    '''
    fileContent = '# THIS IS BUDGET CONFIG FILE\n\n\
# DO NOT EDIT LINE START WITH \'[\'\n\
# FILL CONTENT OF MONTH AND YEAR IN EACH CATEGORY\n\
# THE CONTENT OF MONTH SHOULD BE 12 NUMBERS JOINED BY \',\', REPRESENT BUDGET FOR JAN ~ DEC\n\
# THE CONTENT OF YEAR IS A NUMBER, REPRESENT BUDGET FOR WHOLE YEAR,\n\
# WHICH MUST BE EQUAL OR LARGER THAN SUM OF BUDGET IN EACH MONTH\n\n'
    for item in paymentCat1List:
        if item[2] != 1:
            # 被刪除的項不出現在配置文件中
            continue
        fileContent += '# ' + item[1] + '\n'
        fileContent += '[' + str(item[0]) + ']\n'
        fileContent += 'MONTH = \n'
        fileContent += 'YEAR = \n\n'
    fileContent += '# TOTAL\n[0]\nMONTH = \nYEAR = \n'
    configFile = open(fileAbsoluteName, 'w')
    configFile.write(fileContent)
    configFile.close()
    
def splitBudgetPlan(budgetPlan, currentMonthNumber):
    '''把預算所有內容拆分成當月預算，當月累計預算，年預算
    budgetPlan: 預算列表，格式為：[[NAME, CAT1_ID, MON1 ~ MON12, ALL_YEAR] ...]
    currentMonthNumber: 當前月份
    返回一個列表，格式為[[CAT1_ID, NAME, CUR_MON, CUR_ADDUP, YEAR] ...]
    每個列表的第0個元素代表總預算'''
    indexMonthBegin = 2
    indexMonth = 1 + currentMonthNumber
    indexYear = 14
    monthBudget = []
    monthAddupBudget = []
    yearBudget = []
    ret = []
    for plan in budgetPlan:
        row = []
        row.append(plan[1])
        row.append(plan[0])
        row.append(plan[indexMonth])
        addup = 0
        for i in range(indexMonthBegin, indexMonth + 1):
            addup += plan[i]
        row.append(addup)
        row.append(plan[indexYear])
        ret.append(row)
    return ret
